#define LOG_TAG "libvamem"

#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <sys/epoll.h>

#include <log/log.h>
#include "vamem/vamem.h"

#define VAMEM_GPU_FMT "/dev/gpu_mem_stats"

int init_vamem_monitor() {
    int fd;

    fd = TEMP_FAILURE_RETRY(open(VAMEM_GPU_FMT, O_WRONLY | O_CLOEXEC));
    if (fd < 0) {
        ALOGE("Failed to open vamem_debugfs_path %s (errno=%d)", VAMEM_GPU_FMT, errno);
        return -1;
    }

    ALOGI("vamem monitor init success");
    
    return fd;
}

int register_vamem_monitor(int epollfd, int fd, void* data) {
    int res;
    struct epoll_event epev;

    epev.events = EPOLLPRI;
    epev.data.ptr = data;
    res = epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &epev);
    if (res < 0) {
        ALOGE("epoll_ctl for vamem monitor failed; errno=%d", errno);
    }
    return res;
}

int unregister_vamem_monitor(int epollfd, int fd) {
    return epoll_ctl(epollfd, EPOLL_CTL_DEL, fd, NULL);
}

void destroy_vamem_monitor(int fd) {
    if (fd >= 0) {
        close(fd);
    }
}